package com.atguigu.guli.service.edu.controller.admin;


import com.atguigu.guli.service.base.result.R;
import com.atguigu.guli.service.edu.entity.Subject;
import com.atguigu.guli.service.edu.service.SubjectService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * <p>
 * 课程科目 前端控制器
 * </p>
 *
 * @author yz
 * @since 2022-07-18
 */
@RestController
@RequestMapping("/admin/edu/subject")

public class AdminSubjectController {
    @Autowired
    private SubjectService subjectService;

    //1.删除课程分类
    @ApiOperation("根据id删除课程分类")
    @DeleteMapping("/deleteById/{id}")
    public R deleteById(@PathVariable("id") String id){
        //不能直接删除有二级分类的一级分类
        //如果父ID与传入id相同，说明可以删除
        int count = subjectService.count(new LambdaQueryWrapper<Subject>().eq(Subject::getParentId, id));
        if (count>0){//count大于0说明这个分类下有二级分类 无法直接删除
            return R.error().message("该分类下存在二级分类，删除失败！");
        }
        boolean remove = subjectService.removeById(id);
        return R.ok();
    }

    //2.更新课程分类
    @ApiOperation("更新课程分类")
    @PutMapping("/updateById")
    public R updateById(@RequestBody Subject subject){
        boolean b = subjectService.updateById(subject);
        return R.ok();
    }

    //3.根据课程id查询课程信息
    @ApiOperation("查询课程分类")
    @GetMapping("/getById/{id}")
    public R getById(@PathVariable("id") String id){
        Subject item = subjectService.getById(id);
        return R.ok().data("item",item);
    }

    //4.新增课程分类
    @ApiOperation("新增课程分类")
    @PostMapping("/save")
    public R save(@RequestBody Subject subject){
        boolean b = subjectService.save(subject);
        return R.ok();
    }
    //导入课程分类
    @ApiOperation("导入课程列表")
    @PostMapping("/import")
    public R importSubjects(@ApiParam("导入文件") MultipartFile file){
        subjectService.importSubjects(file);
        return R.ok();
    }
    //查询课程分类
    @ApiOperation("查询一级和二级课程分类集合")
    @GetMapping("/getNestedSubjects")
    public R getNestedSubjects(){
        List<Subject> parents = subjectService.getNestedSubjects();
        return R.ok().data("items",parents);
    }


}

